package com.kly.cashmall.utils.aliyun;

import android.app.Activity;


import com.kly.cashmall.R;
import com.kly.cashmall.base.ParamsBuilder;
import com.kly.cashmall.services.BaseRequest;
import com.kly.cashmall.widget.Loading.LoadingDialog;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author
 * @date 2018/1/13
 */
public class FileOssUpload {

    public interface UploadCallback<T> {
        void success(T t);

        void fail(String msg);
    }

    public static void uploadFile(Activity context, String path, UploadCallback<String> callback) {
        File file = new File(path);
        LoadingDialog.showLoading(context, false);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("picture", file.getName(),
                        RequestBody.create(MediaType.parse("image/jpg"), file))
                .build();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .addHeader("basicParams", ParamsBuilder.create(null, context))
                .url(BaseRequest.baseUrl + "/picture/upload")
                .post(requestBody)
                .build();
        OkHttpClient.Builder builder =
                new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                LoadingDialog.dismissLoading();
                callback.fail(context.getResources().getString(R.string.upload_failed));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    LoadingDialog.dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    String url = jsonObject.getJSONObject("data").getString("url");
                    callback.success(url);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
